import axios from 'axios';
import QS from 'qs';
// import Vue from "vue";

// 环境的切换
let url = process.env.VUE_APP_NEW_URL

axios.defaults.baseURL = url
// 请求超时时间
axios.defaults.timeout = 10000;

// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
axios.interceptors.request.use(
    config => {
      const token = localStorage.getItem('token');
      token && (config.headers.Authorization = token);
      return config;
    },
    error => {
      return Promise.error(error);
    })

// 响应拦截器
axios.interceptors.response.use(
    response => {
      if (response.status === 200 || response.status === 201) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(response);
      }
    },
    // 服务器状态码不是200的情况
    error => {
      if (error.response.status) {
        switch (error.response.status) {
          case 401:
          case 403:
            break;
          case 404:
            break;
          default:
        }
        return Promise.reject(error.response);
      }
    }
);

const api = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      axios.get(url, {
        params: Object.assign({token: localStorage.getItem('token')}, params),
      })
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            reject(err.data)
          })
    });
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, QS.stringify(Object.assign({token: localStorage.getItem('token')}, params)))
          .then(res => {
            resolve(res.data);
          })
          .catch(err => {
            reject(err.data)
          })
    });
  }
}

// 刷新token的请求方法
// function getRefreshTokenFunc() {
//   console.log(12)
//   return
//   let params = {
//     token: localStorage.getItem('token') || ''
//   }
//   return api.post('/userToken/refresh', params)
// }

export default api
